<template>
  <div class="login-page">
    <el-card class="login-card">
      <h2 class="title">公司注册</h2>

      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="register-form"
      >
        <!-- 表单内容保持不变 -->
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="ruleForm.userName"
            placeholder="请输入用户名（3-20位字符）"
            :maxlength="20"
            @input="handleInput('userName')"
          ></el-input>
        </el-form-item>

        <el-form-item label="公司名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入公司全称"
            :maxlength="50"
            @input="handleInput('name')"
          ></el-input>
        </el-form-item>

        <el-form-item label="公司行业" prop="companyIndustry">
          <el-select
            v-model="ruleForm.companyIndustry"
            placeholder="请选择行业"
            clearable
            style="width: 340px"
            @change="handleIndustryChange"
          >
            <el-option
              v-for="item in industries"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在地区" prop="location">
          <localSelect
            v-model="ruleForm.location"
            :city="ruleForm.location"
          ></localSelect>
        </el-form-item>

        <el-form-item label="成立时间" prop="createDate">
          <el-date-picker
            v-model="ruleForm.createDate"
            type="date"
            placeholder="选择成立日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-ddT00:00:00Z"
            :disabled-date="disabledFutureDate"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>

        <el-form-item class="center-button">
          <el-button
            type="primary"
            @click="handleRegister"
            :loading="isLoading"
            :disabled="isLoading"
          >
            立即注册
          </el-button>
        </el-form-item>
      </el-form>

      <div v-if="registerStatus === 'VERIFY_REVIEW'" class="review-tip">
        <el-icon
          class="el-icon-info"
          style="color: #409eff; margin-right: 8px"
        ></el-icon>
        注册信息已提交，等待管理员审核（预计1-3个工作日）
      </div>

      <div v-if="registerStatus === 'VERIFY_FAILED'" class="review-tip error">
        <el-icon
          class="el-icon-warning"
          style="color: #f56c6c; margin-right: 8px"
        ></el-icon>
        审核未通过：{{ reviewFailedMsg }}
      </div>

      <el-button @click="goBack" class="goback">已有账号？返回登录</el-button>
    </el-card>
  </div>
</template>

<script>
// 引入接口（保留）
import { applyRegisterCompany } from "@/api/login";
import { getAllCompanyIndustries } from "@/api/recuriter/register";
import { getVerifyMessage } from "@/api/login"; // 直接引入审核接口
import localSelect from "@/components/localSelect.vue";
import { Message } from "element-ui";
import { mapState } from "vuex";
export default {
  components: { localSelect },
  data() {
    return {
      isLoading: false,
      isSubmitting: false,
      industries: [],

      registerStatus: "Not_SUBMITTED",
      reviewCompanyInfo: {},
      reviewFailedMsg: "",

      ruleForm: {
        userName: "",
        name: "",
        companyIndustry: "",
        location: "",
        createDate: new Date().toISOString().split("T")[0] + "T00:00:00Z",
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 20, message: "长度在3-20位之间", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
        companyIndustry: [
          { required: true, message: "请选择公司行业", trigger: "change" },
        ],
        location: [
          { required: true, message: "请选择所在地区", trigger: "change" },
        ],
        createDate: [
          { required: true, message: "请选择成立时间", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    ...mapState("recruiter", {
      tempToken: (state) => state.tempToken,
    }),
  },
  async created() {
    await this.loadIndustries();
    if (this.tempToken) {
      await this.fetchRegisterStatus();
      if (this.registerStatus === "VERIFY_FAILED") {
        this.ruleForm = { ...this.reviewCompanyInfo };
      } else if (this.registerStatus === "VERIFY_REVIEW") {
        this.isSubmitting = true;
        this.ruleForm = { ...this.reviewCompanyInfo };
      } else {
        this.ruleForm = { ...this.reviewCompanyInfo };
      }
    }
  },

  methods: {
    disabledFutureDate(time) {
      return time.getTime() > Date.now() - 8.64e7;
    },

    handleInput(field) {
      this.ruleForm[field] = this.ruleForm[field].trim();
    },

    async loadIndustries() {
      try {
        const response = await getAllCompanyIndustries();
        if (response?.data?.code === 201) {
          this.industries = response.data.data.map((industry) => ({
            label: industry.industryName || industry.label,
            value: industry.industryName || industry.value,
          }));
        } else {
          Message.error("获取行业列表失败");
        }
      } catch (error) {
        Message.error("获取行业列表失败");
        console.error("行业接口异常:", error);
      }
    },

    async fetchRegisterStatus() {
      if (!this.tempToken) {
        console.log("tempToken为空，无法获取审核状态");
        return;
      }
      try {
        const res = await getVerifyMessage(this.tempToken);
        const { status, companyResp, failedMessage } = res.data.data || {};
        this.registerStatus = status || "Not_SUBMITTED";
        this.reviewCompanyInfo = companyResp || {};
        this.reviewFailedMsg = failedMessage || "";
      } catch (error) {
        console.error("查询审核状态失败", error);
      }
    },

    async handleRegister() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;

        if (!this.tempToken) {
          return Message.error("请先获取临时Token");
        }

        this.isLoading = true;
        try {
          const submitData = {
            userName: this.ruleForm.userName,
            name: this.ruleForm.name,
            companyIndustry: this.ruleForm.companyIndustry,
            location: this.ruleForm.location,
            createDate: this.ruleForm.createDate,
          };
          const response = await applyRegisterCompany(
            submitData,
            this.tempToken
          );
          if (response.data.code === 201) {
            this.isSubmitting = true;
            if (response.data.tempToken) {
              this.$store.commit(
                "recruiter/SET_TEMP_TOKEN",
                response.data.tempToken
              );
            }
            Message.success("注册申请已提交，等待审核");
            this.reviewCompanyInfo = submitData;
            await this.fetchRegisterStatus();
          } else if (response.data.code === 400) {
            Message.error("表单信息有误，请检查");
          }
        } catch (error) {
          Message.error("网络请求失败，请重试");
          console.error("注册接口错误:", error);
        } finally {
          this.isLoading = false;
        }
      });
    },

    goBack() {
      this.$router.push({ path: "/login", query: { userType: "recruiter" } });
    },
  },
};
</script>

<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
  background-image: url(../../../public/image/登录页面背景.png);
  background-size: cover;
  background-position: center;
}

.login-card {
  position: relative;
  padding: 30px 40px 50px;
  width: 500px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  background-color: rgba(255, 255, 255, 0.9);
}

.title {
  text-align: center;
  font-size: 24px;
  color: #409eff;
  margin-bottom: 30px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input__inner {
  height: 48px;
  font-size: 16px;
}

.el-button--primary {
  min-width: 180px;
  height: 50px;
  font-size: 16px;
  border-radius: 8px;
}

.center-button {
  padding-right: 110px;
  margin-bottom: 30px;
}

.goback {
  position: absolute;
  right: 30px;
  bottom: 30px;
  border: none;
  background: transparent;
}

.review-tip {
  margin-top: 40px;
  font-size: 14px;
  line-height: 1.5;
}

.review-tip.error {
  color: #f56c6c;
}
</style>
